package com.wuh.utils;


import com.alibaba.fastjson.JSON;
import com.wuh.model.Message;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/tochat")
@Component
public class MyWebSocket {

    //存放websocket 对象  存放会话
    private static Map<String, Session> onlineSessions = new ConcurrentHashMap<>();


     // 发送信息给所有人
    private static void sendMessageToAll(String msg) {
        onlineSessions.forEach((id, session) -> {
            try {
                session.getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    //打开 连接  更新在线人数
    @OnOpen
    public void onOpen(Session session) {
        onlineSessions.put(session.getId(), session);
        sendMessageToAll(Message.jsonStr(Message.ENTER, "", "","", onlineSessions.size()));
    }
    //  获取用户名和信息 发送
    @OnMessage
    public void onMessage(Session session, String jsonStr) {
        Message message = JSON.parseObject(jsonStr, Message.class);
        sendMessageToAll(Message.jsonStr(Message.SPEAK, message.getUsername(), message.getMsg(),message.getImgu(), onlineSessions.size()));
    }

    //关闭连接 下线
    @OnClose
    public void onClose(Session session) {
        onlineSessions.remove(session.getId());
        sendMessageToAll(Message.jsonStr(Message.QUIT, "", "下线了！","", onlineSessions.size()));
    }


    // 打印错误日志
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }





}
